package com.mxpio.erp.equipment.service.impl;

import com.mxpio.erp.common.enums.CommonEnums;
import com.mxpio.erp.common.equipment.entity.EquipmentCategory;
import com.mxpio.erp.common.equipment.entity.EquipmentEqpBasics;
import com.mxpio.erp.common.equipment.entity.EquipmentEqpRelCategory;
import com.mxpio.erp.common.equipment.service.EquipmentCategoryService;
import com.mxpio.erp.common.equipment.service.EquipmentEqpRelCategoryService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备分类中间表Service业务层处理
 *
 * @author Cheng
 * @date 2023-07-01
 */
@Service
public class EquipmentEqpRelCategoryServiceImpl extends BaseServiceImpl<EquipmentEqpRelCategory> implements EquipmentEqpRelCategoryService {

    @Resource
    private EquipmentCategoryService equipmentCategoryService;

    @Override
    @Transactional(readOnly = true)
    public List<EquipmentEqpBasics> listAllEqpByCategoryId(String categoryId) {
        // 先查询此分类，看是否有子分类
        EquipmentCategory category = JpaUtil.linq(EquipmentCategory.class).equal("code", categoryId).findOne();
        List<EquipmentEqpBasics> tpmEqpBasics = new ArrayList<>();

        if (category == null || category.getIsEnable() == 0) {
            // 返回一个空数组，防止前端处理出错
            return tpmEqpBasics;
        }
        if (CommonEnums.YesNo.NO.getCode().equals(category.getHasChild())) {
            // 无子节点，直接使用eq查询
            tpmEqpBasics = getAllEqpByCategoryIds(categoryId);
        }else {
            // 有子节点，递归查询子节点
            String treeChildIds = equipmentCategoryService.queryTreeChildIds(categoryId);
            if (StringUtils.isBlank(treeChildIds)) {
                // 无实质性子节点
                tpmEqpBasics = getAllEqpByCategoryIds(categoryId);
            }else {
                tpmEqpBasics = getAllEqpByCategoryIds(treeChildIds);
            }
        }
        return tpmEqpBasics;
    }

    @Transactional(readOnly = true)
    public List<EquipmentEqpBasics> getAllEqpByCategoryIds(String categoryIds) {
        List<String> categoryIdList= Arrays.asList(categoryIds.split(","));
        List<EquipmentEqpRelCategory> relCategoryList = JpaUtil.linq(EquipmentEqpRelCategory.class).in("categoryId", categoryIdList).list();
        List<String> basicsCodes = relCategoryList.stream().map(item -> item.getBasicsCode()).collect(Collectors.toList());
        List<EquipmentEqpBasics> basicsList = JpaUtil.linq(EquipmentEqpBasics.class).in("basicsCode", basicsCodes).list();
        return basicsList;
    }
}
